<template>
  <view class="popup-container" :class="{ 'popup-show': visible }">
    <!-- 遮罩层 -->
    <view class="popup-mask" @click="handleClose"></view>
    <!-- 弹窗内容 -->
    <view class="popup-content" v-if="paySuccess">
      <!--  -->
      <view class="flex flex-col p-4">
        <image src="" class="w-20 h-20 mb-2" mode="scaleToFill" />
        <view class="text-center text-lg mb-2">恭喜您拼团成功~</view>
        <view class="text-center text-xs mb-2">现在分享订单给您的好友，快速成团吧~</view>

        <wd-button type="primary" open-type="share" @click="handleShare">
          <text>立即分享</text>
        </wd-button>
      </view>
    </view>
    <!-- 弹窗内容 -->
    <view class="popup-content" v-else>
      <!-- 关闭按钮 -->
      <view class="popup-close" @click="handleClose">
        <text class="close-icon">×</text>
      </view>

      <!-- 标题区域 -->
      <view class="popup-header"></view>

      <!-- 商品信息 -->
      <view class="product-info" v-if="goodsInfo">
        <view class="product-detail">
          <image class="product-image" :src="goodsInfo.image" mode="aspectFill"></image>
          <view class="product-desc">
            <text class="product-name">{{ goodsInfo.name }}</text>
            <text class="product-note">{{ goodsInfo.keyword }}</text>
            <view class="price-quantity">
              <!-- <text class="price" v-if="goodsInfo.isSpell == 1">¥{{ goodsInfo.vipPrice }}</text> -->
              <text class="price">¥{{ goodsInfo.spellPrice }}</text>
              <view class="quantity-control">
                <view class="quantity-btn minus" @click="decreaseQuantity">-</view>
                <text class="quantity-value">{{ quantity }}</text>
                <view class="quantity-btn plus" @click="increaseQuantity">+</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 价格信息 -->
      <view class="price-info">
        <view class="price-row">
          <text class="price-label">商品总价</text>
          <text class="price-value">¥{{ totalPrice }}</text>
        </view>
        <view class="price-row total">
          <text class="total-text">共{{ quantity }}件</text>
          <text class="final-price">
            <text class="text-black text-3">实际支付</text>
            ¥{{ finalPrice }}
          </text>
        </view>
      </view>

      <!-- 协议同意 -->
      <view class="agreement">
        <view class="checkbox" :class="{ checked: agreedToTerms }" @click="toggleAgreement">
          <text v-if="agreedToTerms" class="checkbox-icon">✓</text>
        </view>
        <text class="agreement-text">
          我已阅读并同意《邻里生活荟用户服务协议》《邻里生活荟隐私政策》
        </text>
      </view>

      <!-- 支付按钮 -->
      <view class="pay-button" @click="handlePay">
        <text class="pay-text">立即支付 ¥{{ finalPrice }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { useOrderStore } from '@/store/order'
import { storeToRefs } from 'pinia'
import { ref, computed } from 'vue'
import { http } from '@/utils/http'
import { useInviteStore } from '@/store/invite'
import { useUserStore } from '@/store/user'

const orderStore = useOrderStore()
const { goodsInfo, num } = storeToRefs(orderStore)

const inviteStore = useInviteStore()
// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})

// Emits
const emit = defineEmits(['close', 'pay'])

const paySuccess = ref(false)

// 响应式状态
const quantity = ref(1)
const remark = ref('')
const paymentMethod = ref('wechat')
const agreedToTerms = ref(true)

// 计算属性
const totalPrice = computed(() => {
  return goodsInfo.value.spellPrice * quantity.value
})

const finalPrice = computed(() => totalPrice.value)

// 方法
const handleClose = () => {
  emit('close')
}

const increaseQuantity = () => {
  quantity.value++
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const selectPayment = (method) => {
  paymentMethod.value = method
}

const toggleAgreement = () => {
  agreedToTerms.value = !agreedToTerms.value
}

const groupId = ref(0)

const handlePay = async () => {
  if (!agreedToTerms.value) {
    uni.showToast({
      title: '请先同意用户协议',
      icon: 'none',
    })
    return
  }

  let share = inviteStore.fineInviteCode(goodsInfo.value.id)
  console.log('%c [ share ]-137', 'font-size:13px; background:pink; color:#bf2c9f;', share)

  let data = {
    id: goodsInfo.value.id,
    number: quantity.value,
    remark: '',
    orderType: 2,
    groupId: groupId.value,
    couponId: 0,
    share,
  }

  let res = await http({
    url: '/api/wxPayApplet/productWxPay',
    method: 'POST',
    data: data,
  })

  if (res.code == 200) {
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: res.data.timeStamp,
      nonceStr: res.data.nonceStr,
      package: res.data.package,
      signType: 'MD5',
      paySign: res.data.paySign,
      success: (res) => {
        uni.showToast({
          title: '支付成功',
          icon: 'success',
        })

        emit('pay')
        // emit('close')
        // 状态设置为已支付
        paySuccess.value = true
      },
      fail: (err) => {
        uni.showToast({
          title: '支付失败',
          icon: 'none',
        })
      },
    })
  }
}

const userStore = useUserStore()

const handleShare = () => {
  let path = `/pages/group/product?scene=${goodsInfo.value.id}`

  if (userStore?.userInfo?.invitationCode) {
    path = `/pages/group/product?scene=${goodsInfo.value.id}-${userStore?.userInfo?.invitationCode}`
  }

  uni.showShareMenu({
    title: '邻里生活荟',
    content: goodsInfo.value.name,
    imageUrl: goodsInfo.value.mainImage,
    path,
  })
}

defineExpose({
  groupId,
  handleClose,
  handlePay,
})

</script>

<style>
.popup-container {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  visibility: hidden;
}

.popup-show {
  visibility: visible;
}

.popup-mask {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  background-color: rgba(0, 0, 0, 0.6);
}

.popup-content {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  transition: transform 0.3s ease;
  transform: translateY(100%);
}

.popup-show .popup-content {
  transform: translateY(0);
}

.popup-close {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
}

.close-icon {
  font-size: 48rpx;
  color: #999;
}

.popup-header {
  padding: 20rpx 0 30rpx;
}

.popup-title {
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: 500;
}

.product-info {
  margin-bottom: 30rpx;
}

.product-tag {
  display: inline-block;
  padding: 6rpx 16rpx;
  margin-bottom: 20rpx;
  font-size: 24rpx;
  color: white;
  background-color: #e74c3c;
  border-radius: 6rpx;
}

.product-detail {
  display: flex;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  margin-right: 20rpx;
  border-radius: 8rpx;
}

.product-desc {
  flex: 1;
}

.product-name {
  display: block;
  margin-bottom: 10rpx;
  font-size: 28rpx;
}

.product-note,
.product-discount {
  display: block;
  margin-bottom: 6rpx;
  font-size: 24rpx;
  color: #999;
}

.price-quantity {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
}

.price {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
  font-size: 36rpx;
  border: 1px solid #eee;
}

.quantity-value {
  width: 80rpx;
  font-size: 28rpx;
  text-align: center;
}

.price-info {
  padding: 30rpx 0;
  border-top: 1px solid #f5f5f5;
  border-bottom: 1px solid #f5f5f5;
}

.price-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.price-label {
  font-size: 28rpx;
  color: #333;
}

.price-value {
  font-size: 28rpx;
  font-weight: 500;
}

.coupon-tag {
  display: inline-block;
  padding: 2rpx 8rpx;
  margin-right: 10rpx;
  font-size: 22rpx;
  color: white;
  background-color: #ff5252;
  border-radius: 4rpx;
}

.discount-value {
  font-size: 28rpx;
  color: #ff5252;
}

.total {
  margin-top: 30rpx;
}

.total-text {
  font-size: 26rpx;
  color: #666;
}

.final-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff5252;
}

.remark-section {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
}

.remark-label {
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.remark-input {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.payment-methods {
  margin-bottom: 30rpx;
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.wechat {
  background-color: #07c160;
  border-radius: 50%;
}

.friend {
  background-color: #07c160;
  border-radius: 50%;
}

.payment-name {
  flex: 1;
  font-size: 28rpx;
}

.payment-check {
  font-size: 36rpx;
  color: #07c160;
}

.agreement {
  display: flex;
  align-items: center;
  margin: 30rpx 0;
}

.checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
  border: 1px solid #ddd;
  border-radius: 50%;
}

.checked {
  background-color: #07c160;
  border-color: #07c160;
}

.checkbox-icon {
  font-size: 24rpx;
  color: white;
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
}

.pay-button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  margin-top: 30rpx;
  background-color: #07c160;
  border-radius: 8rpx;
}

.pay-text {
  font-size: 32rpx;
  font-weight: 500;
  color: white;
}
</style>
